﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FichoWeb.Models;
using System.Web.Security;
using System.Net;
using System.Data.Entity;

namespace FichoWeb.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                using (var db = new FichoContext())
                {
                    var user = db.Users.FirstOrDefault(u => u.Username == model.Username && u.Password == model.Password);
                    if (user != null)
                    {
                        user.LastLogin = DateTime.Now;
                        db.Entry(user).State = EntityState.Modified;
                        db.SaveChanges();
                        FormsAuthentication.SetAuthCookie(user.Id.ToString(), false);
                        return RedirectToAction("index", "home");
                    }
                }
            }
            else
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            return View();
        }

    }
}
